package edu.whu.zqm.assignment7.monitor;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class ServiceMonitor {
    private final Map<String, ServiceMonitorData> monitorData = new HashMap<>();

    public Map<String, ServiceMonitorData> getMonitorData() {
        return monitorData;
    }

    public void addMethod(String method, long timeUse, boolean exceptionThrown) {
        ServiceMonitorData data = monitorData.getOrDefault(method, new ServiceMonitorData());
        if (exceptionThrown) {
            data.setExceptionCount(data.getExceptionCount() + 1);
        } else {
            data.setCount(data.getCount() + 1);
            data.setTotalTime(data.getTotalTime() + timeUse);
            if (data.getMaxTime() == null || data.getMaxTime() < timeUse) {
                data.setMaxTime(timeUse);
            }
            if (data.getMinTime() == null || data.getMinTime() > timeUse) {
                data.setMinTime(timeUse);
            }
        }
        monitorData.put(method, data);
    }
}
